package com.test.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

public class CookieDemo01 extends HttpServlet {
    //保存用户上一次访问的时间
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求和相应的编码问题处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 对外输出
        PrintWriter out = resp.getWriter();

        // Cookie，获取 , 数组
        Cookie[] cookies = req.getCookies();

        //判断cookie是否存在
        if(cookies != null){
          //如果存在，便利数组
            for (int i=0; i < cookies.length; i++){
                Cookie cookie = cookies[i];
                if(cookie.getName().equals("lastLoginTime")){
                    // String value = cookie.getValue();
                    //把字符串转换成时间戳
                    long LastLoginTime = Long.parseLong(cookie.getValue());
                    Date date  = new Date(LastLoginTime);
                    out.write(date.toLocaleString());
                }
                if(cookie.getName().equals("username2")){
                    // String value = cookie.getValue();
                    URLDecoder.decode( cookie.getValue(),"utf-8");  //解码
                }
            }

        }else{
            out.write("这是您第一次访问");
        }

        //服务器给客户端相应cookie
        Cookie cookieName = new Cookie("username","mnmnwq");
        Cookie cookieName2 = new Cookie("username2", URLEncoder.encode("小明","UTF-8")); // 中文处理方式
        Cookie cookieTime = new Cookie("lastLoginTime",System.currentTimeMillis() + "");
        // 设置cookie有效期
        cookieName.setMaxAge(24 * 60 * 60);
        cookieTime.setMaxAge(24 * 60 * 60);
        resp.addCookie(cookieName);
        resp.addCookie(cookieTime);
        resp.addCookie(cookieName2);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求和相应的编码问题处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
    }
}
